<?php
// +----------------------------------------------------------------------
// | OneChat
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.tealun.com
// +----------------------------------------------------------------------
// | Author: Tealun Du <tealun@tealun.com> <http://www.tealun.com>
// +----------------------------------------------------------------------

namespace Admin\Controller;

use Think\Db;

/**
 *ONECHAT更新后台管理控制器

 */
class OnechatUpdateController extends AdminController {

    /**
     * 系统升级
     * 在此方法中检测现有系统版本，并从服务器获取最新版本号
     * 通过对比后提醒是否更新系统
     */
    public function index() {
        $this->meta_title = "OneChat系统升级";

        $this->assign('localVersion' , ONECHAT_VERSION);
        $this->checkVersion();
        $this->display();
    }
    /**
     * 更新历史记录
     */
    public function detail() {
        $this->meta_title = "更新历史";
        $this->display();
    }

    /**
     * 检查新版本
     * @author huajie <banhuajie@163.com>
     */
    private function checkVersion(){
        if(extension_loaded('curl')){
            $url = 'http://www.juexin.pro/Home/CheckVersion';
            $params = array(
                'version' => ONECHAT_VERSION,
                'domain'  => $_SERVER['HTTP_HOST'],
                'auth'    => sha1(C('DATA_AUTH_KEY')),
            );
            $vars = http_build_query($params);
            //获取版本数据
            $data = $this->getRemoteUrl($url, 'post', $vars);
            $data = json_decode($data,true);
            if(!empty($data)){
                $this->assign('lastVersion',$data);
            }
        }else{
            $this->error('请配置支持curl');
        }
    }

    /**
     * 获取远程数据
     * @author huajie <banhuajie@163.com>
     */
    private function getRemoteUrl($url = '', $method = '', $param = ''){
        $opts = array(
            CURLOPT_TIMEOUT        => 20,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_URL            => $url,
            CURLOPT_USERAGENT      => $_SERVER['HTTP_USER_AGENT'],
        );
        if($method === 'post'){
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $param;
        }

        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data  = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        return $data;
    }
}